<?php
/**
 * Copyright (c) 2018-2019.
 *  This file is part of the moonpie production
 *  (c) johnzhang <875010341@qq.com>
 *  This source file is subject to the MIT license that is bundled
 *  with this source code in the file LICENSE.
 */

namespace moonpie\plugin\wechat_account\model;


use app\common\service\data\ArrayDataProvider;
use EasyWeChat\Kernel\Support\Arr;
use moonpie\plugin\wechat_account\service\template\NullParser;
use moonpie\plugin\wechat_account\service\template\TemplateVarParserInterface;
use moonpie\plugin\wechat_account\service\user\WechatUserInterface;
use think\Cache;
use think\Hook;

/**
 * 管理公众号模板相关的模型
 * Class TemplateModel
 * @package moonpie\plugin\wechat_account\model
 */
class TemplateModel
{
    private $account;
    /** @var TemplateVarParserInterface */
    private $parser;
    protected function getCacheKey()
    {
        $cache_key = 'official_all_private_templates:' . $this->getAccount()->getService()->getId();
        return $cache_key;
    }
    public function __construct(WechatAccount $account)
    {
        $this->account = $account;
    }
    public function getAccount()
    {
        return $this->account;
    }
    public function listTemplates()
    {
        /** @var \EasyWeChat\OfficialAccount\Application $app */
        $app = $this->getAccount()->getService();
        $cache_key = $this->getCacheKey();
        $templates = Cache::get($cache_key, false);
        if(false === $templates) {
            $response = $app->template_message->getPrivateTemplates();
            if(isset($response['template_list'])){
                $templates = $response['template_list'];
                Cache::set($cache_key, $templates, 86400 * 7);
            }else {
                return false;
            }
        }
        return $templates;
    }
    public function clearCache()
    {
        $cache_key = $this->getCacheKey();
        if(Cache::has($cache_key)) {
            return Cache::rm($cache_key);
        }
        return true;
    }
    public function dataProvider($listRows = null, $simple = false, $options = [])
    {
        $templates = $this->listTemplates();
        if(!$templates) $templates = [];
        return new ArrayDataProvider([
            'paginationConfig' => compact('listRows', 'simple', 'options'),
            'allModels' => $templates,
        ]);
    }
    public function findByTmplId($tmplId)
    {
        if(empty($tmplId)) return false;
        $templates = $this->listTemplates();
        if(false !== $templates) {
            return array_filter($templates, function($template)use($tmplId){
                return $template['template_id'] == $tmplId;
            });
        }
        return null;
    }

    /**
     * 给指定的用户发送模板消息
     * @param WechatUserInterface $user
     * @param $template
     * @param array $templateVars
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    public function sendTemplate(WechatUserInterface $user, $template, $templateVars = [])
    {
        $parser = $this->getTemplateParser();
        $data = $parser->parse($templateVars);
        //这里处理一下url和miniprogram
        if(empty(Arr::get($data, 'miniprogram.appid'))) {
            unset($data['miniprogram']);
        }
        if(empty(Arr::get($data, 'url'))) unset($data['url']);
        $data['touser'] = $user->getOpenid();
        $data['template_id'] = $template['template_id'];
        $service = $this->getAccount()->getService();
        $response = $service->template_message->send($data);
        $params = compact('user', 'template', 'data', 'response');
        $params['target'] = $this;
        Hook::listen('system.send_template_message', $params);
        return $response;
    }
    public function getTemplateParser()
    {
        if(is_null($this->parser)){
            $this->parser = new NullParser();
        }
        return $this->parser;
    }

    /**
     * @param TemplateVarParserInterface $parser
     */
    public function setParser($parser)
    {
        if(is_null($parser) || $parser instanceof TemplateVarParserInterface) {
            $this->parser = $parser;
        }
    }

}